package com.huawei.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huawei.domain.LoginUser;
import com.huawei.entity.Users;
import com.huawei.mapper.MenusMapper;
import com.huawei.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private MenusMapper menusMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Users> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUsername, username);

        //根据用户名获取用户信息
        Users user = usersMapper.selectOne(wrapper);
        //使用Hutool工具包来判断是否为空
        if(ObjectUtil.isNull(user))
            throw new RuntimeException("用户名或密码不对 请重新输入喵~");

        //设置用户的权限列表
        List<String> userAuthorityList =menusMapper.getPermsByUserId(user.getId());

        return LoginUser.builder()
                        .user(user)
                        .permissions(userAuthorityList)
                        .build();
    }
}
